﻿using iTool.ClusterComponent;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace iTool.ClusterComponent
{
    public class LimitWorkUnitProvider : IWorkUnitProvider
    {
        public IWorkScopeProvider WorkScopeProvider { get; }
        public ILimitingService LimitingService { get; }
        private long Limit { get; }
        public LimitWorkUnitProvider(long limit, IWorkScopeProvider workScopeProvider) 
        {
            this.WorkScopeProvider = workScopeProvider;
            this.Limit = limit;
            this.LimitingService = this.GetLimitingService();
        }

        public Task ApplyExcuterAsync() => this.LimitingService.ApplyExcuterAsync();

        public void Dispose()
        {
            _ = this.DisposeAsync();
        }

        public async ValueTask DisposeAsync()
        {
            await this.WorkScopeProvider.NextAsync();
            await this.LimitingService.FreedOneAsync();
            GC.SuppressFinalize(this);
        }


        private ILimitingService GetLimitingService() 
        {
            return this.WorkScopeProvider.ClusterService.GetService<ILimitingService>(this.Limit, this.WorkScopeProvider.WorkScopeName);
        }
    }
}
